#!/usr/bin/perl

use DBI;

$SRC_DB=$ENV{'SRC_DB'};
$TGT_DB=$ENV{'TGT_DB'};

sub select_node
{
#	print "select_node.node:$_[0]\n";
	$t_node = $_[0];

	$db = DBI->connect('DBI:ODBC:'.$SRC_DB, 'hubiio', 'hubiio');

	$sql = "
SELECT
-- B.MSG_ID,
-- D.APP_ID,
-- D.SUBN_ID,
-- D.CHG_ACT,
-- E.OPT_SEQ_NUM,
A.APP_NAME,
C.RULE_NAME || ',' ||
E.OPT_VAL,
F.OPT_VAL,
G.OPT_VAL,
H.OPT_VAL
FROM 	NNR_APP A,
	NNR_MSG_MSTR B,
	NNR_RULE C,
	NNR_SUBN_MSTR D,
	NNR_SUBN_ACT E,
	NNR_SUBN_ACT F,
	NNR_SUBN_ACT G,
	NNR_SUBN_ACT H,
(
SELECT
	E.APP_ID,
	E.MSG_ID,
	E.SUBN_ID,
MIN(E.ACT_SEQ_NUM) AA,
MAX(E.ACT_SEQ_NUM) BB
FROM 	
	NNR_SUBN_ACT E
WHERE
-------------------------------
	E.ACT_NAME = 'Reformat'
GROUP BY
	E.APP_ID,
	E.MSG_ID,
	E.SUBN_ID
) AA
WHERE
B.MSG_ID = C.MSG_ID
AND	A.APP_NAME = '$app_name'
AND	C.RULE_ACTIVE = '1'
AND	C.RULE_NAME = '$rule_name'
AND	A.APP_ID = C.APP_ID
AND	D.APP_ID = C.APP_ID
AND	D.MSG_ID = C.MSG_ID
AND	D.RULE_ID = C.RULE_ID
-------------------------------
 AND	AA.APP_ID = D.APP_ID
 AND	AA.MSG_ID = D.MSG_ID
 AND	AA.SUBN_ID = D.SUBN_ID
-------------------------------
AND	E.APP_ID = D.APP_ID
AND	E.MSG_ID = D.MSG_ID
AND	E.SUBN_ID = D.SUBN_ID
AND	E.ACT_SEQ_NUM =AA.AA
AND	E.OPT_SEQ_NUM ='1'
-------------------------------
AND	F.APP_ID = D.APP_ID
AND	F.MSG_ID = D.MSG_ID
AND	F.SUBN_ID = D.SUBN_ID
AND	F.ACT_SEQ_NUM =AA.AA
AND	F.OPT_SEQ_NUM ='3'
-------------------------------
AND	G.APP_ID = D.APP_ID
AND	G.MSG_ID = D.MSG_ID
AND	G.SUBN_ID = D.SUBN_ID
AND	G.ACT_SEQ_NUM =AA.BB
AND	G.OPT_SEQ_NUM ='1'
-------------------------------
AND	H.APP_ID = D.APP_ID
AND	H.MSG_ID = D.MSG_ID
AND	H.SUBN_ID = D.SUBN_ID
AND	H.ACT_SEQ_NUM =AA.BB
AND	H.OPT_SEQ_NUM ='3'
-------------------------------
--GROUP BY C.RULE_NAME || ',' || E.OPT_VAL
-- A.APP_NAME, B.MSG_NAME, C.RULE_NAME,
--  E.OPT_VAL, F.OPT_VAL
-- ORDER BY E.OPT_VAL,
-- F.OPT_VAL
";
  	$sth = $db->prepare($sql);

#print ">>>>$sql<<<<\n";
	$sth->execute();
  
	$i=0;
	while(@data = $sth -> fetchrow_array){
    		#print "[$i] ";
#    		print "[$i],$data[0],$data[1],$data[2],$data[3]";
#    		print ",$data[4],$data[5]\n";
		if( @ARGV[0] == 0 ) {
    			print "[$i],$data[0],";
    			print "$data[1],";
    			print "$data[2],";
    			print "$data[3],";
    			print "$data[4],";
    			print "$data[5]\n";
		} else {
#    			print "[$i],$data[0] $data[1] $data[2] $data[3] $data[4] $data[5]\n";
   			print "$data[0]\n";
		}

		$s_data00[$i] = $data[0];
		$s_data01[$i] = $data[1];
		$s_data02[$i] = $data[2];
		$s_data03[$i] = $data[3];
		$s_data04[$i] = $data[4];
		$s_data05[$i] = $data[5];

    	#	print "|i:$i $s_data00[$i]\n";

		$i += 1;
	}

	$sth->finish;
	$db->disconnect;
}

$app_name = @ARGV[0];
$rule_name = @ARGV[1];

&select_node;
